package cn.cxq.learning.e3_2;

public class EXPUtil {
    private static final double EPOW10 = 22026.465794806717;

    private static double expTV(double x) {
        int N = 23;
        int K = 0;
        double y = 1.0;
        if (x <= 0.5) N = 14;
        else if (x <= 1.0) N = 18;
        else N = 23;
        for (K = N; K > 0; K--)
            y = 1.0 + y * x / K;
        return y;
    }

    public static double exp(double x) {
        int TYPE = 0;
        double y0 = 1.0;
        if (x < 0) {
            TYPE = 1;
            x = -x;
        }
        while (true) {
            if (x > 10) {
                x -= 10;
                y0 *= EPOW10;
            } else if (x > 2) {
                x -= 2;
                y0 *= expTV(2);
            } else break;
        }
        y0 *= expTV(x);
        if (TYPE == 1) return 1.0 / y0;
        else return y0;
    }
}
